<?php

require_once ROOT_SERVICES . DS . 'shipping_provider_interface.php';
require_once ROOT_LIBRARY_HTMLDOM . DS . 'simple_html_dom.php';
require_once ROOT_LIBRARY_CURL . DS . 'curl.php';
require_once ROOT_LIBRARY_CURL . DS . 'curl_response.php';
require_once ROOT_SERVICES_HELPER . DS . 'curl.php';

// Thai post
class shipping_provider_2 implements shipping_provider_interface {

    private $_shipment;

    public function __construct($shipment) {
        $this->_shipment = $shipment;
    }

    public function get_status_shipping() {
        try
        {
            $tracking_number = $this->_shipment ['tracking_number'];
            $url = $this->_shipment ['url'] !== '' ? $this->_shipment ['url'] : "http://www.tnt.com/webtracker/tracking.do?respCountry=us&respLang=en&navigation=1&page=1&sourceID=1&sourceCountry=ww&plazaKey=&refs=&requesttype=GEN&searchType=CON&cons={$tracking_number}";
            $html = str_get_html(curl::instance()->get($url));
			if($html){
				$table_p_e = $html->find('#content table', 3);
				$status_list = array();
				ini_set('default_charset', 'UTF-8');

				if (is_object($table_p_e)) {
					$table_content = $table_p_e->find('table.appTable', 1);
					if (is_object($table_content)) {
						foreach ($table_content->find('tr') as $tr) {
							if (is_object($tr)) {
								$tds = $tr->find('td');
								if (is_array($tds)) {
									$date = array_shift($tds);
									$time = array_shift($tds);
									$location = array_shift($tds);
									$status = array_shift($tds);

									list($d, $M, $Y) = sscanf(trim($date->plaintext), '%02d %03s %04d');
									list($H, $s, $i) = sscanf(trim($time->plaintext), '%02d:%02s:%02d');

									$month = array('Jan' => 01, 'Feb' => 02, 'Mar' => 3, 'Apr' => 04,
										'May' => 05, 'Jun' => 06, 'Jul' => 07, 'Aug' => 08,
										'Sep' => 09, 'Oct' => 10, 'Nov' => 11, 'Dec' => 12);

									if ($M && $H) {
										$status_list[] = array(
											'time' => "{$Y}-{$month["$M"]}-{$d} {$H}:{$i}:{$s}",
											'status' => trim(strip_tags($status->plaintext))
										);
									}
								}
							}
						}
					}
				}
			}
            return array('sortable' => TRUE, 'status_list' => $status_list);
        } catch (Exception $e)
        {
            return array('sortable' => FALSE, 'status_list' => null);
        }
    }

}

?>
